package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Override
    public String upload(MultipartFile file) {
        String url = "";

        try {
            //使用 MinIO Java SDK 构建一个 MinIO 客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioConstantProperties.getEndpointUrl())  // 设置 MinIO 服务器地址
                    .credentials(minioConstantProperties.getAccessKey(),  // 设置访问密钥（用户名）
                            minioConstantProperties.getSecreKey())       // 设置私有密钥（密码）
                    .build();  // 构建 MinioClient 实例
            boolean found = false;
            //检查指定的 MinIO 存储桶（Bucket）是否存在
            found = minioClient.bucketExists(
                    BucketExistsArgs.builder()
                            .bucket(minioConstantProperties.getBucketName()).build());
            //如果不存在则创建
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioConstantProperties.getBucketName()).build());
                //如果已存在则提示重复创建
            } else {
                System.out.println("Bucket：" + minioConstantProperties.getBucketName() + "重复创建");
            }
            //名字格式：<随机UUID（无横线）>.<文件原始扩展名>
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." +
                    FilenameUtils.getExtension(file.getOriginalFilename());

            minioClient.putObject(  // 调用 MinIO 客户端的上传方法
                    PutObjectArgs.builder()  // 构建上传参数
                            .bucket(minioConstantProperties.getBucketName())  // 指定目标存储桶
                            .object(fileName)  // 设置存储的文件名（唯一标识）
                            .stream(file.getInputStream(), file.getSize(), -1)  // 文件流和大小
                            .contentType(file.getContentType())  // 设置文件的 MIME 类型（如 image/jpeg）
                            .build()  // 构建参数对象
            );

            url = minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + fileName;
            System.out.println("url:\t" + url);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        return url;
    }
}
